<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 输入框位置 -->
      <el-row :gutter="10" type="flex" justify="space-between">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" class="addUser">
          <el-button type="primary" class="addUserBtn" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格数据展示 -->
      <el-table :data="usersList" border style="width: 100%">
        <el-table-column align="center" type="index" label="序号"></el-table-column>
        <el-table-column align="center" prop="username" label="姓名"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱"></el-table-column>
        <el-table-column align="center" prop="mobile" label="电话"></el-table-column>
        <el-table-column align="center" prop="role_name" label="角色"></el-table-column>
        <el-table-column align="center" prop="mg_state" label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="mg_state" label="操作" width="200px">
          <template v-slot="operation">
            <!-- 修改用户信息 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(operation.row)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(operation.row)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="info"
                icon="el-icon-setting"
                @click="setRoles(operation.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        @close="CloseListening('addFormRef')"
        width="60%"
        :close-on-click-modal="false"
        :lock-scroll="false"
      >
        <!-- :model 是绑定的表单数据对象,:rules 是验证规则对象,规则名称和表单绑定的名称一样 ,ref是表单的引用对象 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="dialogVisible_Edit"
        width="60%"
        :lock-scroll="false"
        :close-on-click-modal="false"
        @close="CloseListening('editFormRef')"
      >
        <el-form :model="editForm" :rules="editUserRules" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input disabled v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_Edit = false">取 消</el-button>
          <el-button type="primary" @click="EditSubmit()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRolesdialogVisible"
        width="400px"
        :lock-scroll="false"
        :close-on-click-modal="false"
        @close="setRolesClose"
      >
        <div class="container">
          <p>
            <font color="green">当前用户名 :</font>
            {{userInfo.username}}
          </p>
          <p>
            <font color="green">当前角色 :</font>
            {{userInfo.role_name}}
          </p>
          <p>
            <font color="green">角色 :</font>
            <el-select v-model="selectRolesId" clearable placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSetRoles">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[\w\-]+@[a-zA-Z\d\-]+(\.[a-zA-Z]{2,8}){1,2}$/gi;
      if (!value) {
        callback(new Error("邮箱不能为空"));
      } else {
        if (!regEmail.test(value)) {
          callback("请输入正确的邮箱地址");
        }
        callback();
      }
    };
    //验证手机号
    var checkTel = (rule, value, callback) => {
      // 验证手机号码的正则表达式
      const regTel = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/;
      if (!value) {
        callback(new Error("手机号不能为空"));
      } else {
        if (!regTel.test(value)) {
          callback("请输入正确的手机号码");
        }
        callback();
      }
    };

    return {
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        //当前显示多少条
        pagesize: 2
      },
      usersList: [],
      total: 0,
      addDialogVisible: false, //控制t添加用户对话框的显示和隐藏
      dialogVisible_Edit: false, //控制修改用户对话框
      setRolesdialogVisible: false, //控制角色的对话框
      addForm: {
        //添加用户的数据区域
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addFormRules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 5,
            max: 12,
            message: "用户名长度要求在5-12位",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          },
          { min: 6, max: 12, message: "密码长度要求在6-12位", trigger: "blur" }
        ],
        email: [
          {
            required: true,
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          {
            required: true,
            validator: checkTel,
            trigger: "blur"
          }
        ]
      },
      editForm: {
        //修改用户的数据区域
        id: "",
        email: "",
        mobile: ""
      },
      editUserRules: {
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur"
          },
          {
            min: 5,
            max: 12,
            message: "用户名长度要求在5-12位",
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          {
            required: true,
            validator: checkTel,
            trigger: "blur"
          }
        ]
      },
      userInfo: {},
      rolesList: [],
      selectRolesId: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("/users", {
        params: this.queryInfo
      });
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      // 监听每页显示的条数改变的时候触发
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      //监听页码被点击的时候 页码值
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async changeUserState(_userInfo) {
      const { data: res } = await this.$http.put(
        `/users/${_userInfo.id}/state/${_userInfo.mg_state}`
      );
      const result = res.meta;

      if (result.status == 200) {
        this.$message({
          showClose: true,
          message: result.msg,
          type: "success"
        });
      } else {
        this.$message({
          showClose: true,
          message: result.msg,
          type: "success"
        });
      }
    },
    CloseListening(_ref) {
      // 监听dialog弹出框关闭的时候触发,清空数据和重置验证规则
      this.$refs[_ref].resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message({
            showClose: true,
            message: "温馨提示:  您输入信息有误,请您检查。",
            type: "warning"
          });
          return false;
        }
        // 前端验证通过的话发送ajax请求服务端添加数据
        const { data: res } = await this.$http.post("/users", this.addForm);
        if (res.meta.status == 201) {
          // 添加用户成功
          this.$message({
            showClose: true,
            message: `温馨提示:   ${res.data.username + `   ` + res.meta.msg}`,
            type: "success"
          });
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          //添加用户失败
          console.log(res);
          this.$message({
            showClose: true,
            message: "很遗憾:添加用户失败了!   " + res.meta.msg,
            type: "error"
          });
        }
      });
    },
    async showEditDialog(_userInfo) {
      // 修改展示用户信息对话框
      const { data: searchResult } = await this.$http.get(
        "/users/" + _userInfo.id
      );
      if (searchResult.meta.status !== 200) {
        this.$message.error("出错了,查询不到用户信息!");
        return;
      }
      //把数据赋值到修改的数据对象里面,并且获取过来的数据中带有id
      this.editForm = searchResult.data;
      this.dialogVisible_Edit = true;
    },
    EditSubmit() {
      // 修改用户信息之后点击提交
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          //前端检验不通过则不发起ajax请求
          this.$message({
            showClose: true,
            message: "温馨提示:  您输入信息有误,请您检查。",
            type: "warning"
          });
          return false;
        }

        //利用axios发起ajax请求
        const { data: res } = await this.$http.put(
          "/users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        );
        if (res.meta.status == 200) {
          //关闭弹出框
          this.dialogVisible_Edit = false;
          // 更新成功提示
          this.$message({
            showClose: true,
            message: "更新成功",
            type: "success"
          });
          //刷新列表数据
          this.getUserList();
        } else {
          //更新失败提示
          this.$message({
            showClose: true,
            message: "更新失败",
            type: "error"
          });
        }
      });
    },
    deleteUser(_userInfo) {
      // 删除用户的
      const that = this;
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          const { data: res } = await that.$http.delete(
            "/users/" + _userInfo.id
          );
          console.log(res);
          if (res.meta.status != 200) {
            that.$message({
              showClose: true,
              message: "删除失败",
              type: "error"
            });
            return;
          }
          that.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          that.getUserList();
        })
        .catch(() => {});
    },
    async setRoles(_userInfo) {
      // 分配角色
      //获取所有角色列表
      const { data: res } = await this.$http.get("/roles");
      this.rolesList = res.data;
      this.userInfo = _userInfo;
      this.setRolesdialogVisible = true;
    },
    async submitSetRoles() {
      if (!this.selectRolesId) {
        this.$message.warning("请您先选择角色在提交!");
        return;
      }
      const { data: res } = await this.$http.put(
        "/users/" + this.userInfo.id + "/role",
        {
          rid: this.selectRolesId
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("设置权限失败了!");
        return;
      }
      this.$message.success("设置权限成功!");
      this.setRolesdialogVisible = false;
      this.getUserList();
    },
    setRolesClose() {
      this.selectRolesId = "";
    }
  }
};
</script>
<style scoped>
.el-table {
  margin-top: 20px;
}
.addUserBtn {
  float: right;
}
.pagination {
  margin-top: 10px;
}
.el-dialog {
  min-width: 400px;
}
.container {
  padding-left: 30px;
  font-weight: bold;
}
.container > p > font {
  margin-right: 20px;
  font-size: 14px;
  font-weight: bold;
}
</style>